import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import an8 from '@mmstudio/an000008';
import { tbjob, tbjobpublish, tbproject, tbs_job_ment, tbstudent } from '../../../../atoms/db';

const logger = anylogger('pages/api/zllweapp/zuoyefabu/s003.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	selectedclasses: string[];

	id: string;
}

/**
 * pages/api/zllweapp/zuoyefabu/s003.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);

		const { selectedclasses, id } = req.body as Message;
		if (!selectedclasses) {
			res.status(200).json({ ok: false, message: '班级参数错误' });
			return;
		}
		//**所布置班级的所有学生数据 */
		const data = await tbstudent().select('student_id', 'name').whereIn(
			'class_id', selectedclasses
		);

		/**字符串数组转化为对象的方法 ---- */
		await tbjobpublish().insert(selectedclasses.map((it) => {
			return {
				job_id: id,
				class_id: it,
				punlishstatus: 2
			};
		}));

		await tbjob().insert(data.map((it) => {
			return {
				job_id: id,
				studentname: it.name,
				student_id: it.student_id,
				sjob_id: an8(),

			};
		}));
		await tbs_job_ment().insert(data.map((it) => {
			return {
				job_id: id,
				studentname: it.name,
				student_id: it.student_id,


			};
		}));

		/**等效上 */
		// const data = selectedclasses.map((it) => {
		// 	return {
		// 		job_id,
		// 		class_id: it,
		// 		punlishstatus: 2
		// 	};
		// });
		// await tbjobpublish().insert(data);


		res.status(200).json({ ok: true });
	} catch (error) {
		logger.error(error);
		res.status(200).json({ ok: false, message: 'error' });
	}
});

export const config = {} as PageConfig;

export default handler;
